package com.hm.service.api.main;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.entity.user.UserBean;
import com.hm.service.framework.PostController;
import com.hm.service.service.main.CaptchaService;
import com.hm.service.service.main.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


@RestController
@RequestMapping(value = "/MAIN", produces = {"application/json;charset=UTF-8"})
public class SZCG_000_000_002 extends PostController {
    private static final Logger logger = LoggerFactory.getLogger(SZCG_000_000_002.class);

    private final UserService userService;

    private final CaptchaService captchaService;

    //登录接口
    public SZCG_000_000_002(UserService userService, CaptchaService captchaService) {
        this.userService = userService;
        this.captchaService = captchaService;
    }

    @PostMapping(value = "/000_000_002")
    public String doPost(HttpServletRequest request) {
        return handleRequest(request);
    }

    @Override
    protected String postRequest(HashMap<String, String> param) {
        String requestBody = param.get("requestBody");
        JSONObject jsonObject = (JSONObject) JSON.parse(requestBody);
        String captchaKey = jsonObject.getString("captchaKey");
        String captcha = jsonObject.getString("captcha");
        String userName = jsonObject.getString("userName");
        String userPwd = jsonObject.getString("pwd");
        //非空判断
        if (captcha == null || captcha.isEmpty()) {
            return generateFail("验证码为空");
        }
        if (userName == null || userName.isEmpty() || userPwd == null || userPwd.isEmpty()) {
            return generateFail("用户名或密码为空");
        }
        //验证码
        HashMap<String, String> captchaVerify = captchaService.verify(captcha, captchaKey);
        if (!captchaVerify.get("state").equals("000")) {
            return generateFail(captchaVerify.get("msg"));
        }
        //用户->查库
        UserBean userBean = userService.getUserForName(userName);
        if (userBean == null) {
            return generateFail("用户不存在");
        }
        String pwd = userBean.userPwd;
        if (!pwd.equals(userPwd)) {
            return generateFail("密码错误");
        }
        //完成->颁发token
        Long userId = userBean.userId;
        String token = generateToken(String.valueOf(userId));
        //封装响应体
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("accessToken", token);
        resMap.put("userName", userBean.userName);
        return generateSucceed(resMap);
    }
}
